<template>
    <ul class="category-list" @mouseleave="outHover()">
        <li
            class="category-item active"
            id="category_0"
            :data-index="0"
            @mouseover="hoverIndex(0)"
        >
            <nuxt-link :to="{ path: '/blog' }">全部</nuxt-link>
        </li>
        <li
            class="category-item"
            :id="`category_` + item.id"
            v-for="(item, index) in list"
            :key="item.id"
            :data-index="index + 1"
            @mouseenter="hoverIndex(item.id)"
        >
            <nuxt-link :to="{ path: '/blog', query: { category: item.id } }">
                {{ item.title }}
            </nuxt-link>
        </li>

        <li class="category-silder"></li>
    </ul>
</template>

<script>
export default {
    name: "category-list",
    props: {
        list: {
            type: [Array],
        },
    },
    data() {
        return {
            id: this.$route.query.category,
            hover: false,
        };
    },
    watch: {
        // 监听路由变化
        $route(to) {
            this.id = to.query.category;
            this.onClickCategory(to.query.category);
        },
    },
    mounted() {
        this.onClickCategory(this.id);
    },
    methods: {
        /* hover下划线跟随 */
        hoverIndex(id) {
            let $liCur = $("#category_" + id)[0];
            let $slider = $(".category-silder");

            $slider.css("top", $liCur.offsetTop);

            this.hover = true;
        },

        /* hover介绍下划线回到原位置 */
        outHover() {
            if (this.hover) {
                let $liCur = $(".category-item.active")[0];
                let $slider = $(".category-silder");

                $slider.css("top", $liCur.offsetTop);

                this.hover = false;
            }
        },

        /* 点击选中添加active */
        onClickCategory(id) {
            id = id ? id : 0;
            let $liCur = $("#category_" + id);
            let $slider = $(".category-silder");
            $liCur.addClass("active").siblings().removeClass("active");
            let active = $(".category-item.active")[0];

            $slider.css("top", active.offsetTop);
        },
    },
};
</script>

<style lang="less" scoped>
.category-list {
    position: relative;
    margin: 15px 0;

    .category-item {
        padding: 0 20px;
        height: 40px;
        line-height: 40px;
        position: relative;
        z-index: 1;

        &:first-child {
            padding: 0;
        }

        a {
            display: block;
            padding: 0 20px;
            font-size: 16px;
            font-weight: 600;
            color: #606f7b;
            font-family: sans-serif;
        }
    }

    .category-silder {
        position: absolute;
        width: 100%;
        height: 40px;
        border-right: 0.375rem solid #525251;
        background-color: #f8f8f7;
        transition: top 0.3s;
        z-index: 0;
        top: 0;
        left: 0;
    }
}
</style>